<template>
    <van-popup
        v-model:show="show"
        position="bottom">
        <van-picker
            ref="areapicker"
            :title="$t('wp-di-qu')"
            :columns="areaOptions"
            @confirm="onConfirm"
            @cancel="onCancel"
            @change="areaChange">
        </van-picker>
    </van-popup>
</template>
<script>
import { selfI18n } from '@/i18n/index';
import { computed, reactive, toRefs, watch, ref, toRef } from 'vue';
import { deviceviewSetup } from '@/setup/deviceview/deviceviewSetup.js';

export default {
    props: {
        areaShow: Boolean,
        region: Object
    },
    emits: ['onAreaCancel', 'onAreaConfirm'],
    setup (props, ctx) {
        const region = toRef(props, 'region');
        const $st = selfI18n;
        const areapicker = ref(null);
        const { getProductarchiveAddressArea } = deviceviewSetup();
        // computed
        const state = reactive({
            areaOptions: [{
                values: [$st('wp-qing-xuan-ze')],
                defaultIndex: 0
            }, {
                values: [$st('wp-qing-xuan-ze')],
                defaultIndex: 0
            }, {
                values: [$st('wp-qing-xuan-ze')],
                defaultIndex: 0
            }],
            areaObj: {
                country: '',
                province: '',
                city: ''
            },
            chooseValues: areapicker.value && areapicker.value.getValues()
        });

        const show = computed(() => {
            return props.areaShow;
        });

        // 地区变化
        const areaChange = (area, index) => {
            getArea(area, index);
        };

        // 地区选择器获取areaname和administrativelevel
        const getAreanameAndLevel = (area, index) => {
            const arr = [$st('wp-qing-xuan-ze')];
            if (area[0] === $st('wp-qing-xuan-ze')) {
                areapicker.value && areapicker.value.setColumnValues(1, arr);
                areapicker.value && areapicker.value.setColumnValues(2, arr);
                return {
                    administrativelevel: '',
                    areaname: '',
                    index: 0
                };
            }
            if (area[0] !== $st('wp-qing-xuan-ze') && area[1] === $st('wp-qing-xuan-ze')) {
                return {
                    administrativelevel: 'country',
                    areaname: area[0],
                    index: 1
                };
            }
            if (index === 0) {
                areapicker.value && areapicker.value.setColumnValues(1, arr);
                areapicker.value && areapicker.value.setColumnValues(2, arr);
                return {
                    administrativelevel: 'country',
                    areaname: area[0],
                    index: 1
                };
            }
            if (area[1] !== $st('wp-qing-xuan-ze')) {
                return {
                    administrativelevel: 'province',
                    areaname: area[1],
                    index: 2
                };
            }
        };

        const getArea = (area, index, defaultType) => {
            return new Promise((resolve, reject) => {
                const param = getAreanameAndLevel(area, index);
                getProductarchiveAddressArea(param).then((data) => {
                    const arr = data.value;
                    arr.unshift($st('wp-qing-xuan-ze'));
                    areapicker.value && areapicker.value.setColumnValues(param.index, arr);
                    state.areaOptions[param.index].values = arr;
                    if (defaultType === 'defaultIndex') {
                        setDefaultIndex(param.index);
                    }
                    resolve(data);
                });
            });
        };

        const setDefaultIndex = (index) => {
            const indexObj = {
                0: state.areaObj.country,
                1: state.areaObj.province,
                2: state.areaObj.city
            };
            state.areaOptions[index].defaultIndex = state.areaOptions[index].values.findIndex(item => item === indexObj[index]);
        };

        const onConfirm = (value) => {
            state.areaObj.country = value[0] === $st('wp-qing-xuan-ze') ? '' : value[0];
            state.areaObj.province = value[1] === $st('wp-qing-xuan-ze') ? '' : value[1];
            state.areaObj.city = value[2] === $st('wp-qing-xuan-ze') ? '' : value[2];
            ctx.emit('onAreaConfirm', state.areaObj);
        };

        const onCancel = () => {
            ctx.emit('onAreaCancel');
        };

        const initValue = async () => {
            if (region.value === undefined) {
                ctx.emit('update:region', {
                    country: '',
                    province: '',
                    city: ''
                });
                return;
            }
            state.areaObj.country = region.value.country;
            state.areaObj.province = region.value.province;
            state.areaObj.city = region.value.city;
            if (state.areaObj.country) {
                await getArea([$st('wp-qing-xuan-ze'), $st('wp-qing-xuan-ze'), $st('wp-qing-xuan-ze')], 0, 'defaultIndex');
                await getArea([state.areaObj.country, $st('wp-qing-xuan-ze'), $st('wp-qing-xuan-ze')], 1, 'defaultIndex');
            }
            if (state.areaObj.province) {
                await getArea([state.areaObj.country, state.areaObj.province, $st('wp-qing-xuan-ze')], 2, 'defaultIndex');
            }
        };

        watch([show, region], (newValue, oldValue) => {
            if (newValue[0] && !newValue[1]) {
                getArea([$st('wp-qing-xuan-ze'), $st('wp-qing-xuan-ze'), $st('wp-qing-xuan-ze')]);
                areapicker.value && areapicker.value.setColumnIndex(0, 0);
            } else if (newValue[0] && newValue[1]) {
                initValue();
            }
        }, { immediate: true }, { deep: true });

        return {
            ...toRefs(state),
            show,
            areapicker,
            areaChange,
            onConfirm,
            onCancel
        };
    }
};
</script>
